# Virtual Router Simulator 
#
# Copyright (C) 2009-2010 VRSim Project
# Author: Choonho Son <choonho@kt.com>
# URL: <http://vrsim.googlecode.com>
# For license information, see LICENSE.TXT
#

import VRSim.Globals as globals
import datetime
from PyQt4 import QtGui,  QtCore
from VRSim.Ui.Ui_Project import Ui_Project


class Project(QtGui.QDialog,  Ui_Project):
    def __init__(self,  page=1):
        QtGui.QDialog.__init__(self)
        Ui_Project.__init__(self)
        self.setupUi(self)
        self.item = ["Project",  "Hypervisors",  "Miscellaneous"]
        self.itemDesc = {"Project": "Basic Configuration for your simulation", 
                         "Hypervisors": "Multiple Hypervisors configuration", 
                         "Miscellaneous": "Miscellaneous configuration"}
        self.initItem(page)
        self.__connectActions()
        
        self.lineEdit_Directory.setEnabled(False)
        self.pushButton_Directory.setEnabled(False)
        
    # init left menu 
    # page 1: Project
    # page 2: Hypervisors
    def initItem(self,  page):
        self.treeWidget_Menu.setHeaderLabels(["Configuration"])
        
        for item in self.item:
            rootitem = QtGui.QTreeWidgetItem(self.treeWidget_Menu)
            rootitem.setText(0, item)
            self.treeWidget_Menu.insertTopLevelItem(0,  rootitem)
        
        if page == 1:
            self.stackedWidget.setCurrentWidget(self.page_Project)
            self.groupBox_Detail.setTitle( self.itemDesc["Project"])
        elif page == 2:
            # change page
            # chage title
            self.stackedWidget.setCurrentWidget(self.page_Hypervisors)
            self.groupBox_Detail.setTitle( self.itemDesc['Hypervisors'] )
        elif page == 3:
            # change page
            # change title
            self.stackedWidget.setCurrentWidget(self.page_Misc)
            self.groupBox_Detail.setTitle( self.itemDesc["Miscellaneous"])
            
        self.initProject()
        self.initHypervisors()
        self.initMisc()
    
    def __connectActions(self):
        # left menu
        self.connect(self.treeWidget_Menu,  QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"),  self.__action_menuClicked)
        
        # Signal for Working directory
        self.connect(self.pushButton_Directory,  QtCore.SIGNAL('clicked()'),  self.__action_Directory)
        # Signal for Project page
        self.connect(self.pushButton_File,  QtCore.SIGNAL('clicked()'),  self.__action_filechoose)
        self.connect(self.comboBox_Location,  QtCore.SIGNAL('currentIndexChanged(int)'),  self.updateLocation)
        
        # Signals for Hypervisors page
        self.connect(self.pushButton_Verify,  QtCore.SIGNAL('clicked()'),  self.__action_verify)
        
        # Signals for Miscellaneous
        self.connect(self.pushButton_Terminal,  QtCore.SIGNAL('clicked()'),  self.__action_terminal)
        
        # Signal for OK, Cancel
        self.connect(self.buttonBox,  QtCore.SIGNAL('accepted()'),  self.__save )
        #self.connect(self.buttonBox,  QtCore.SIGNAL('rejected()'),  self.close )
        
    def __action_menuClicked(self,  item):
        # change detail title
        index = str( item.text(0))
        self.groupBox_Detail.setTitle( self.itemDesc[ index ] )
        
        if index == "Project":
            self.stackedWidget.setCurrentWidget(self.page_Project)
            
        elif index == "Hypervisors":
            self.stackedWidget.setCurrentWidget(self.page_Hypervisors)
        elif index == "Miscellaneous":
            self.stackedWidget.setCurrentWidget(self.page_Misc)
        
    def __action_Directory(self):
        dirname = QtGui.QFileDialog.getExistingDirectory(self,  "Choose Working directory",  globals.baseDir)
        if dirname:
            self.lineEdit_Directory.setText(dirname)
        
    def __action_filechoose(self):
         filename = QtGui.QFileDialog.getSaveFileName(self,  "Save Topology Config file",  globals.baseDir,  "XML files (*.xml);;All files (*.*)")
         if filename:
            self.lineEdit_Filename.setText(filename)
    
    def __action_verify(self):
        # verify each hypervisor for test
        hypervisors = []
        for index in range(8):
            name = self.tableWidget_Hypervisors.item(index,  0)
            if not name:
                break
            type = self.tableWidget_Hypervisors.item(index,  1)
            uri = self.tableWidget_Hypervisors.item(index,  2)
            vmuri = self.tableWidget_Hypervisors(index, 3)
            # TODO: test each hypervisor
            # 1. connection
            # 2.
            hypervisor = [ name.text(),  type.text(),  uri.text(),  vmuri.text() ]
            hypervisors.append(hypervisor)
            
        # Add to self.hypervisors
        globals.GApp.topology.hypervisors = hypervisors
        
    def __save(self):
        # working_directory
        working_directory = self.lineEdit_Directory.text()
        if working_directory:
            globals.working_directory = str(working_directory)
        # filename
        
        filename = self.lineEdit_Filename.text()
        #if filename == "":
        #    reply = QtGui.QMessageBox.question(self, 'Message',"Define configuration file first!", QtGui.QMessageBox.Yes)
        #    return
        
        # TODO: file writable?
        if filename:
            globals.saveFilename = filename
        
        # save configuration
        #location
        globals.GApp.topology.location = str(self.comboBox_Location.currentText())
        globals.GApp.topology.geoX = str( self.lineEdit_baseX.text() )
        globals.GApp.topology.geoY = str( self.lineEdit_baseY.text() )
        # Designer
        globals.GApp.topology.designer = str( self.lineEdit_Designer.text() )
        # Date
        globals.GApp.topology.date = str ( self.lineEdit_Date.text() )
     
    # initialize Basic configuration page
    def initProject(self):
        # project directory
        if globals.working_directory:
            self.lineEdit_Directory.setText(str(globals.working_directory))
        # configuration file
        if globals.saveFilename:
            filename_en = unicode(globals.saveFilename)
            self.lineEdit_Filename.setText(filename_en)
        
        key = globals.GApp.topology.location
        # Location
        count = 0
        self.comboBox_Location.clear()
        for where in globals.baseLocation.keys():
            self.comboBox_Location.addItem(where)
            if key == where:
                self.comboBox_Location.setCurrentIndex(count)
            count = count + 1
        # update location
        location = globals.baseLocation[key]
        self.lineEdit_baseX.setText(str(location[0]))
        self.lineEdit_baseY.setText(str(location[1]))
        
        designer = globals.GApp.topology.designer
        self.lineEdit_Designer.setText(designer)
        
        date = globals.GApp.topology.date
        if date:
            self.lineEdit_Date.setText(str(date))
        else:
            today = datetime.date.today()
            self.lineEdit_Date.setText(str(today))
     
    # update location selection from comboBox_Location
    def updateLocation(self,  index):
        where = str( self.comboBox_Location.currentText() )
        location = globals.baseLocation[where]
        self.lineEdit_baseX.setText( str(location[0]) )   # X 
        self.lineEdit_baseY.setText( str(location[1]) )   # Y
        
    # initialize hypervisors page
    def initHypervisors(self):
        # width of each cells
        self.tableWidget_Hypervisors.setColumnWidth(0,  70)
        self.tableWidget_Hypervisors.setColumnWidth(1,  70)
        self.tableWidget_Hypervisors.setColumnWidth(2,  150)
        
        # default item
        row = 0
        
        for item in globals.GApp.topology.hypervisors:
            # item = ['name', 'type', 'uri', 'vmapi uri']
            item1 = QtGui.QTableWidgetItem(item[0])
            item2 = QtGui.QTableWidgetItem(item[1])
            item3 = QtGui.QTableWidgetItem(item[2])
            item4 = QtGui.QTableWidgetItem(item[3])
            self.tableWidget_Hypervisors.setItem(row, 0,  item1)
            self.tableWidget_Hypervisors.setItem(row, 1,  item2)
            self.tableWidget_Hypervisors.setItem(row, 2,  item3)
            self.tableWidget_Hypervisors.setItem(row, 3,  item4)
            row = row + 1
        

    def initMisc(self):
        """ init miscellaneous page
        """
        # terminal
        self.lineEdit_Terminal.setText(globals.TERMINAL)
        
    def __action_terminal(self):
        filename = QtGui.QFileDialog.getSaveFileName(self,  "Choose Telnet terminal",  globals.baseDir,  "EXE files (*.exe);;All files (*.*)")
        if filename:
            globals.TERMINAL = filename
            self.lineEdit_Terminal.setText(filename)
